#if UNITY_STANDALONE || UNITY_ANDROID || UNITY_IOS || UNITY_WSA || UNITY_WEBGL
using BuildComponent;
using GameDesigner;
using Net.Common;
using Net.Component;
using Net.Share;
using Net.UnityComponent;
using UnityEngine;

namespace Example1
{
    public class PlayerFsm : NetworkBehaviour
    {
        public StateMachineView view;
        public float moveSpeed = 6f;

        public override void OnNetworkInitialize(in Operation opt)
        {
            NetworkSceneManager.Instance.RegisterOperationCommand(Identity, OnOperationHandler); //注册玩家切换状态指令
            StateMachineSystem.AddStateController(view.controller);
            view.Init();
        }

        public override void OnDestroy()
        {
            NetworkSceneManager.Instance?.RemoveOperationCommand(Identity, OnOperationHandler); //移除玩家切换状态指令
            StateMachineSystem.RemoveStateController(view.controller);
        }

        private void OnOperationHandler(in Operation opt)
        {
            if (IsLocal)
                return;
            switch (opt.cmd)
            {
                case OperCommand.SwitchState:
                    view.controller.ChangeState(opt.cmd1);
                    break;
            }
        }
    }

    public class IdleState : StateBehaviour
    {
        private PlayerFsm self;

        public override void OnInit()
        {
            self = transform.GetComponent<PlayerFsm>();
        }

        public override void OnFirstEnter()
        {
            NetworkSceneManager.I.AddOperation(new Operation(OperCommand.SwitchState, self.Identity)
            {
                cmd1 = 0
            });
        }

        public override void OnUpdate()
        {
            if (!self.IsLocal)
                return;
            var dir = Camera.main.transform.Transform3Dir();
            if (dir != Vector3.zero)
            {
                ChangeState(1);
            }
        }
    }

    public class RunState : StateBehaviour
    {
        private PlayerFsm self;

        public override void OnInit()
        {
            self = transform.GetComponent<PlayerFsm>();
        }

        public override void OnFirstEnter()
        {
            NetworkSceneManager.I.AddOperation(new Operation(OperCommand.SwitchState, self.Identity)
            {
                cmd1 = 1
            });
        }

        public override void OnUpdate()
        {
            if (!self.IsLocal)
                return;
            var dir = Camera.main.transform.Transform3Dir();
            if (dir != Vector3.zero)
            {
                transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(dir, Vector3.up), 0.5f);
                transform.Translate(0, 0, self.moveSpeed * Time.deltaTime);
            }
            else
            {
                ChangeState(0);
            }
        }
    }
}
#endif